package baseclass.c_globalToPartMatrix;

/**
 * * 给定正方形矩阵，旋转90度
 * 分析：
 * 局部,给定一个局部正方形，左上角[a,b] 右下角[c,d] ，旋转90:每个点围绕正方形中心转90度
 * 全局：左上角往右下角缩，右下角往左上角缩，直到 a>c或者b>d
 * <p>
 * <p>
 * 【要求】 额外空间复杂度为O(1)
 *
 * @date 2020/2/27 22:32
 */
public class Code02_Rotate90 {
    public static void printMatrix(int[][] matrix) {
        for (int i = 0; i != matrix.length; i++) {
            for (int j = 0; j != matrix[0].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12},
                {13, 14, 15, 16}};
        printMatrix(matrix);
        rotate(matrix);
        System.out.println("=========");
        printMatrix(matrix);

    }

    public static void rotate(int[][] m) {
        int a = 0;
        int b = 0;
        int c = m.length - 1;
        int d = m[0].length - 1;
        while (a < c) {
            doRotate(m, a++, b++, c--, d--);
        }
    }

    public static void doRotate(int[][] m, int a, int b, int c, int d) {
        for (int i = 0; i < d - b; i++) {
            int temp = m[a][b + i];
            m[a][b + i] = m[c - i][b];
            m[c - i][b] = m[c][d - i];
            m[c][d - i] = m[a + i][d];
            m[a + i][d] = temp;
        }
    }
}
